package Service.Impl;

//import Model.permission.HappyPermissionMapper;
import Dao.RoleMapper;
//import com.smartcity.dao.permission.HappyRolePermissionMapper;
//import Model.permission.HappyPermission;
import Model.permission.*;
import Service.RoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.List;

@Service("RoleService")
public class RoleServiceImpl implements RoleService {

  private static final Logger logger = LoggerFactory
      .getLogger(RoleServiceImpl.class);


  @Resource
  private RoleMapper roleMapper;
  @Override
  public List<Role> roleList() {
    return this.roleMapper.findList();
  }

  @Override
  public RoleVO findRoleAndPerms(Integer id) {
    return this.roleMapper.findRoleAndPerms(id);
  }

  @Override
  public List<Permission> findPerms() {
     return this.roleMapper.findPerms();
  }

  @Override
  public List<Integer> selectPermissionIdOfRole(int roleId) {
    return roleMapper.selectPermissionIdOfRole(roleId);
  }

  @Override
  public List<Permission> selectPermissionOfRole(int roleId) {
    return roleMapper.selectPermissionOfRole(roleId);
  }

  @Override
  @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout = 30000,rollbackFor = {RuntimeException.class, Exception.class})
  public Boolean addRole(Role role, String permIds){
    this.roleMapper.insert(role);
    role = this.roleMapper.getRolesByInsertTime().get(0);//就是找回刚刚插入的那条记录
    int roleId = role.getId();//这里应该是要查找刚刚插入的那条数据
    String[] arrays = permIds.split(",");
    logger.debug("权限id =arrays="+ arrays.toString());
    setRolePerms(roleId,arrays);
    return true;
  }

  @Override
  public boolean updatePerm(Permission permission) {
    return this.roleMapper.updateByPrimaryKeySelectivePerm(permission) == 1;
  }

  @Override
  public Permission addPermission(Permission permission) {
    if(this.roleMapper.insertPerm(permission) >0 ){
      return permission;
    }
    return null;
  }

  @Override
  public Permission getPermission(int id) {
    return this.roleMapper.selectByPrimaryKeyPerm(id);
  }

  @Override
  public List<Permission> getUserPerms(Integer id) {
    return roleMapper.getUserPerms(id);
  }

  @Override
  public String delPermission(int id) {
    //查看该权限是否有子节点，如果有，先删除子节点
    List<Permission> childPerm = this.roleMapper.findChildPerm(id);
    if(null != childPerm && childPerm.size() > 0){
      return "删除失败，请您先删除该权限的子节点！";
    }
    if(this.roleMapper.deleteByPrimaryKeyPerm(id) > 0){
      return "ok";
    }else{
      return "删除失败，请您稍后再试！";
    }
  }

  @Override
  @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=30000,rollbackFor={RuntimeException.class, Exception.class})
  public Boolean updateRole(Role role, String permIds) {
    int roleId= role.getId();
    String[] arrays=permIds.split(",");
    System.out.println("权限id =arrays="+arrays.toString());
    //1，更新角色表数据：
    int num=this.roleMapper.updateByPrimaryKeySelective(role);
//    System.out.println("num:"+num);
    if(num<1){
      //事务回滚
      TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      return false;
    }
    //2，删除原角色权限；
    batchDelRolePerms(roleId);
    //3，添加新的角色权限数据；
    setRolePerms(roleId, arrays);
    System.out.println("ok");
    return true;
  }

  @Override
  @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout = 300000,rollbackFor = {RuntimeException.class, Exception.class})
  public Boolean delRole(int id) {
    //1.删除角色对应的权限
    batchDelRolePerms(id);
    //2.删除角色
    int num = this.roleMapper.deleteByPrimaryKey(id);
    if(num<1){
      //事务回滚
      TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      return false;
    }
    return true;
  }


  /**
   * 给当前角色设置权限
   * @param roleId
   * @param arrays
   */
  private void setRolePerms(int roleId, String[] arrays) {
    System.out.println("来到setRolePerms;");
    for (String permid : arrays) {
      RolePermissionKey rpk=new RolePermissionKey();
      System.out.println("rpk:"+rpk);
      System.out.println("roleId:"+roleId+"  Integer.valueOf(permid):"+Integer.valueOf(permid));
      rpk.setRoleId(roleId);
      rpk.setPermitId(Integer.valueOf(permid));
      System.out.println("rpk.setRoleId:"+rpk.getPermitId());
      this.roleMapper.insert1(rpk);
      System.out.println("成功insert");
    }
  }
  /**
   * 批量删除角色权限中间表数据
   * @param roleId
   */
  private void batchDelRolePerms(int roleId) {
    System.out.println("来到batchDelRolePerms;");
    System.out.println("roleId为："+roleId);
    List<RolePermissionKey> rpks=this.roleMapper.findByRole(roleId);
    System.out.println("rpks:"+rpks.size());
    if(rpks.size()>0){
      for (RolePermissionKey rpk : rpks) {
        System.out.println("rpk:"+rpk.getRoleId());
        this.roleMapper.deleteByPrimaryKey1(rpk);
        System.out.println("成功删除");
      }
    }
  }



}
